package com.woniuxy.zuui.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LimitFilter extends ZuulFilter {

    //创建限流器，令牌算法限流器，指定令牌数量
    private static final RateLimiter RATELIMITER = RateLimiter.create(500);


    //指定filter类型:pre
    @Override
    public String filterType() {
        return "pre";
    }

    //filter执行顺序
    @Override
    public int filterOrder() {
        return 100;
    }
    //对接下面run方法
    @Override
    public boolean shouldFilter() {
        //登录权限
        //上下文對象context
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        //判断uri是否需要什么权限

        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("过滤器执行");
        //上下文對象不处理请求
        if(!RATELIMITER.tryAcquire()){
            RequestContext context = RequestContext.getCurrentContext();
            context.setSendZuulResponse(false);
        }

        return null;
    }
}
